import {defineStore} from 'pinia'
import {SET_TOKEN, GET_TOKEN, REMOVE_TOKEN, GET_ID} from '@/utils/token'
import {LoginFormData, ResponseData, UserState} from "@/api/user/type";
import {reqLogin, reqUserInfo} from "@/api/user";
import router from '@/router'
import {constantRouter, asyncRoute, anyRoute} from '@/router/routes'

// @ts-ignore
import cloneDeep from 'lodash/cloneDeep'

let dynamicRoutes = []

function filterAsyncRoute(asyncRoute: any, routes: any) {
    return asyncRoute.filter((item: any) => {
        if (routes.includes(item.name)) {
            if (item.children && item.children.length > 0) {
                item.children = filterAsyncRoute(item.children, routes)
            }
            return true
        }
    })
}

let useUserStore = defineStore('User', {
    state: (): UserState => {
        return {
            token: GET_TOKEN()!,
            menuRoutes: constantRouter,
            id: GET_ID()!,
            userName: "",
            userAvatar: "",
            userType: ""
        }
    },
    // 异步|逻辑的地方
    actions: {
        //用户登录方法
        async userLogin(data: LoginFormData) {
            let res: ResponseData = await reqLogin(data)
            // success=>token
            // error=>error.message
            if (res.code == 0) {
                this.token = res.data.token as string
                this.id = res.data.userList.id as string
                this.userName = res.data.userList.userName as string
                this.userAvatar = res.data.userList.userAvatar as string
                // 持久化
                SET_TOKEN(res.data.token as string, res.data.userList.id as string)
                return 'ok'
            } else {
                return Promise.reject(new Error(res.message as string))
            }
        },
        async userInfo() {
            let  routes = []
            let res: ResponseData = await reqUserInfo(this.id)
            this.userName = res.data.userName as string
            this.userAvatar = res.data.userAvatar as string
            this.userType = res.data.userType as string
            if(res.data.userType == 'admin'){
                routes = [ 'Screen','Users','Share','Merchants','Cart','Favorite','MyOrder','Product','Order']
            }else if(res.data.userType == 'merchant'){
                routes = [ 'Screen','Cart','Product','Order']
            }else {
                routes = ['Screen','Share','Cart','Favorite','MyOrder']
            }
            let userAsyncRoute = filterAsyncRoute(
                cloneDeep(asyncRoute),
                routes
            )
            this.menuRoutes = [...constantRouter, ...userAsyncRoute, anyRoute]
            dynamicRoutes = [...userAsyncRoute, anyRoute] // 记录动态添加的路由
            dynamicRoutes.forEach((route) => {
                router.addRoute(route) // 动态添加路由
            })
        },
        async userLogout() {
            REMOVE_TOKEN()
            dynamicRoutes.forEach((route) => {
                router.removeRoute(route.name)
            })
        },
    },
    getters: {},
})

export default useUserStore
